package com.yonyou.jrmob.contacts.contact.utils;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/8/10.
 */
public class ContactsUtil_ct {
    private Context context;

    public ContactsUtil_ct(Context context){
        this.context = context;
    }
    /**
     * 添加联系人
     * 在同一个事务中完成联系人各项数据的添加
     * 使用ArrayList<ContentProviderOperation>，把每步操作放在它的对象中执行
     * */
    public void AddContacts(String contactName,String contactPho,String contactEmail,String contactDept){
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = context.getContentResolver();
        // 第一个参数：内容提供者的主机名
        // 第二个参数：要执行的操作
        ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

        // 操作1.添加Google账号，这里值为null，表示不添加
        ContentProviderOperation operation = ContentProviderOperation.newInsert(uri)
                .withValue("account_name", null)// account_name:Google账号
                .build();

        // 操作2.添加data表中name字段
        uri = Uri.parse("content://com.android.contacts/data");
        ContentProviderOperation operation2 = ContentProviderOperation.newInsert(uri)
                // 第二个参数int previousResult:表示上一个操作的位于operations的第0个索引，
                // 所以能够将上一个操作返回的raw_contact_id作为该方法的参数
                .withValueBackReference("raw_contact_id", 0)
                .withValue("mimetype", "vnd.android.cursor.item/name")
                .withValue("data2", contactName)
                .build();

        // 操作3.添加data表中phone字段
        uri = Uri.parse("content://com.android.contacts/data");
        ContentProviderOperation operation3 = ContentProviderOperation.newInsert(uri)
                .withValueBackReference("raw_contact_id", 0)
                .withValue("mimetype", "vnd.android.cursor.item/phone_v2")
                .withValue("data2", "2")
                .withValue("data1", contactPho)
                .build();

        // 操作4.添加data表中的Email字段
        uri = Uri.parse("content://com.android.contacts/data");
        ContentProviderOperation operation4 = ContentProviderOperation
                .newInsert(uri).withValueBackReference("raw_contact_id", 0)
                .withValue("mimetype", "vnd.android.cursor.item/email_v2")
                .withValue("data2", "2")
                .withValue("data1", contactEmail)
                .build();


        // 操作4.添加data表中的organization字段
        uri = Uri.parse("content://com.android.contacts/data");
        ContentProviderOperation operation5 = ContentProviderOperation
                .newInsert(uri).withValueBackReference("raw_contact_id", 0)
                .withValue("mimetype", "vnd.android.cursor.item/organization")
                .withValue("data2", "2")
                .withValue("data1", contactDept)
                .build();

        operations.add(operation);
        operations.add(operation2);
        operations.add(operation3);
        operations.add(operation4);
        operations.add(operation5);

        try {
            resolver.applyBatch("com.android.contacts", operations);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取联系人
     * */
    public boolean searchContacts(String contactName,String contactPho){
        boolean isExist = false;//默认不存在
        String name  = "";
        String phone = "";
        Uri uri = Uri.parse("content://com.android.contacts/contacts"); // 访问所有联系人
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(uri, new String[]{"_id"}, null, null, null);
        while(cursor.moveToNext()){
            int contactsId = cursor.getInt(0);
            //StringBuilder sb = new StringBuilder("contactsId=");
            //sb.append(contactsId);
            uri = Uri.parse("content://com.android.contacts/contacts/" + contactsId + "/data"); //某个联系人下面的所有数据
            Cursor dataCursor = resolver.query(uri, new String[]{"mimetype", "data1", "data2"}, null, null, null);
            while(dataCursor.moveToNext()){
                String data = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                String type = dataCursor.getString(dataCursor.getColumnIndex("mimetype"));
                if("vnd.android.cursor.item/name".equals(type)){    // 如果他的mimetype类型是name
                    name = data;
                } else if("vnd.android.cursor.item/phone_v2".equals(type)){ // 如果他的mimetype类型是phone
                    phone= data ;
                }
            }
            if(contactName.equals(name) && contactPho.equals(phone)){

                isExist = true;
                break;
            }else {
                isExist = false;
            }
        }
        return isExist;
    }

	/*public void coverUpdate(){

		int id = 1;
		String phone = "999999";
		Uri uri = Uri.parse("content://com.android.contacts/data");//对data表的所有数据操作
		ContentResolver resolver = context.getContentResolver();
		ContentValues values = new ContentValues();
		values.put("data1", phone);
		resolver.update(uri, values, "mimetype=? and raw_contact_id=?", new String[]{"vnd.android.cursor.item/phone_v2",id+""})

	}*/

    public void toContactsEdit(boolean isNewAdd, String contactName,String contactPho,String contactTel,String contactEmail,String contactDept) {
        Intent it;
        if (isNewAdd){
            it = new Intent(Intent.ACTION_INSERT, Uri.withAppendedPath(
                    Uri.parse("content://com.android.contacts"), "contacts"));
            it.setType("vnd.android.cursor.dir/person");
            it.setType("vnd.android.cursor.dir/contact");
            it.setType("vnd.android.cursor.dir/raw_contact");
        }else{
            it = new Intent(Intent.ACTION_INSERT_OR_EDIT);
            it.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
            /*it.putExtra(android.provider.ContactsContract.Intents.Insert.PHONE, contactPho);
            it.putExtra(android.provider.ContactsContract.Intents.Insert.PHONE_TYPE, 3);*/
            /*context.startActivity(it);
            if(it.resolveActivity(context.getPackageManager()) != null){
                context.startActivity(it);
            }else{

            }*/
        }



        // 联系人姓名
        it.putExtra(ContactsContract.Intents.Insert.NAME,
                contactName);
        // 公司
        it.putExtra(ContactsContract.Intents.Insert.COMPANY,
                contactDept);
        // email
        it.putExtra(ContactsContract.Intents.Insert.EMAIL,
                contactEmail);
        // 手机号码
        it.putExtra(ContactsContract.Intents.Insert.PHONE,
                contactPho);
        // 单位电话
        it.putExtra(
                ContactsContract.Intents.Insert.SECONDARY_PHONE,
                contactTel);
        /*// 住宅电话
        it.putExtra(
                android.provider.ContactsContract.Intents.Insert.TERTIARY_PHONE,
                "010-7654321");
        // 备注信息
        it.putExtra(android.provider.ContactsContract.Intents.Insert.JOB_TITLE,
                "名片");*/

        context.startActivity(it);
    }

}
